<template>
	<view class="storeSetting">
		<u-toast ref="uToast" /><u-no-network></u-no-network>
		<u-navbar title="店铺设置" safeAreaInsetTop fixed placeholder>
			<view class="coreshop-navbar-left-slot" slot="left">
				<u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="home" size="22" @click="goHome"></u-icon>
			</view>
			<view slot="right">
			</view>
		</u-navbar>
		<view class="coreshop-padding-10 ">
			<u--form :model="form" :rules="rules" ref="uForm" errorType="message" labelPosition="left" labelWidth="80">
				<u-form-item label="店铺名称" prop="storeName" borderBottom>
					<u--input type="text" placeholder='请输入店铺名称' v-model="form.storeName" />
				</u-form-item>
				<u-form-item label="店铺Logo 640*640" borderBottom>
					<!-- <image class='coreshop-avatar xl radius bg-gray' mode="aspectFill" :src="form.storeLogo" @click="uploadLogo"></image> -->
					<u-upload :fileList="storeLogo1" @afterRead="addLogoImg" @delete="deleteLogoImg" name="1" multiple
						:maxSize="2 * 1024 * 1024" :maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label="收款码640*640" borderBottom>
					<u-upload :fileList="paymentCode1" @afterRead="addImg" @delete="deletePaymentCodePic" name="1"
						multiple :maxSize="2 * 1024 * 1024" :maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label="店铺招牌640*200">
					<!--<u-upload :action="upLoadAction" ref="uUpload" :file-list="fileList" max-count="3" :max-size="2 * 1024 * 1024" width="280" height="120" :header="header"></u-upload>-->
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxSize="2 * 1024 * 1024" width="200" height="113" :maxCount="1"></u-upload>
				</u-form-item>
				<u-form-item label="店铺简介" prop="storeDesc" borderBottom>
					<u--textarea v-model="form.storeDesc" placeholder="请您在此描述问题(最多200字)" maxlength="200"
						count></u--textarea>
				</u-form-item>
			</u--form>
		</view>
		<!--按钮-->
		<view class="coreshop-bg-white coreshop-footer-fixed coreshop-foot-padding-bottom">
			<u-button type="error" size="normal" @click="submitHandler">保存</u-button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				upLoadAction: this.$globalConstVars.apiBaseUrl + '/Api/Common/UploadImages',
				header: {
					'Accept': 'application/json',
					'Content-Type': 'multipart/form-data',
					'Authorization': 'Bearer ' + this.$db.get('userToken')
				},
				fileList1: [],
				paymentCode1: [],
				storeLogo1: [],
				form: {
					storeName: '', //店铺名称
					storeLogo: '/static/images/common/add.jpeg',
					storeBanner: '',
					storeDesc: '无', //店铺介绍
				},
				rules: {
					storeName: [{
						required: true,
						message: '请输入店铺名称',
						trigger: ['blur', 'change']
					}],
					storeDesc: [{
						required: true,
						message: '请输入店铺简介',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			//this.fileList = this.$refs.uUpload.lists;
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log(event);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].thumb)
					var jmResult = JSON.parse(result);
					console.log(result);
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: jmResult.data.src
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.upLoadAction, // 仅为示例，非真实的接口地址
						fileType: 'image',
						filePath: url,
						header: {
							'Accept': 'application/json',
							'Content-Type': 'multipart/form-data',
							'Authorization': 'Bearer ' + this.$db.get('userToken')
						},
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			},
			// 收款码 删除图片
			deletePaymentCodePic(event) {
				this[`paymentCode${event.name}`].splice(event.index, 1)
			},
			// 收款码 新增图片
			async addImg(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`paymentCode${event.name}`].length
				lists.map((item) => {
					this[`paymentCode${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].thumb)
					var jmResult = JSON.parse(result);
					console.log(result);
					let item = this[`paymentCode${event.name}`][fileListLen]
					this[`paymentCode${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: jmResult.data.src
					}))
					fileListLen++
				}
			},
			// 店铺Logo
			async addLogoImg(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`storeLogo${event.name}`].length
				lists.map((item) => {
					this[`storeLogo${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].thumb)
					var jmResult = JSON.parse(result);
					console.log(result);
					let item = this[`storeLogo${event.name}`][fileListLen]
					this[`storeLogo${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: jmResult.data.src
					}))
					fileListLen++
				}
			},
			// 店铺Logo 删除图片
			deleteLogoImg(event) {
				this[`storeLogo${event.name}`].splice(event.index, 1)
			},
			/* uploadLogo() {
                this.$upload.uploadFiles(null, res => {
                    if (res.status) {
                        this.form.storeLogo = res.data.src;
                    } else {
                        this.$u.toast(res.msg)
                    }
                })
            }, */
			//保存
			submitHandler() {
				this.$refs.uForm.validate().then(res => {
					if (!this.form.storeName || this.form.storeName == '') {
						this.$u.toast('请填写店铺名称');
						return;
					}
					if (this.storeLogo1.length <= 0) {
						this.$u.toast('请上传店铺LOGO');
						return;
					}
					if (this.fileList1.length <= 0) {
						this.$u.toast('请上传店铺招牌');
						return;
					} else {
						let images = [];
						for (var i = 0; i < this.fileList1.length; i++) {
							if (this.fileList1[i].url) {
								images.push(this.fileList1[i].url);
							} else if (this.fileList1[i].error == false) {
								images.push(this.fileList1[i].response.data.fileUrl);
							}
						}
						this.form.storeBanner = images.join(',');
					}

					// if (!this.form.storeLogo || this.form.storeLogo=='/static/images/common/add.jpeg') {
					//     this.$u.toast('请上传店铺LOGO');
					//     return;
					// }

					this.$u.api.setDealerStore({
						storeName: this.form.storeName,
						storeLogo: this.storeLogo1[0].url,
						storeBanner: this.form.storeBanner,
						storeDesc: this.form.storeDesc,
						paymentCode: this.paymentCode1[0].url,
					}).then(res => {
						if (res.status) {
							this.$refs.uToast.show({
								message: res.msg,
								type: 'success',
								back: false
							})
						} else {
							this.$u.toast(res.msg);
						}
					});

				}).catch(errors => {
					uni.$u.toast('提交的数据校验失败，请输入合法信息！')
				})
			}
		},
		onLoad: function() {
			var _this = this;
			_this.$u.api.getDealerInfo().then(res => {
				if (res.status) {
					_this.form.storeName = res.data.storeName;
					_this.form.storeDesc = res.data.storeDesc || '';
					// _this.form.storeLogo = res.data.storeLogo || '/static/images/common/add.jpeg';
					if (res.data.storeLogo) _this.storeLogo1.push({
						url: res.data.storeLogo
					});
					_this.form.storeBanner = res.data.storeBanner;
					if (res.data.paymentCode) _this.paymentCode1.push({
						url: res.data.paymentCode
					});
					if (res.data.storeBanner) {
						var arr = res.data.storeBanner.split(',');
						for (var i = 0; i < arr.length; i++) {
							_this.fileList1.push({
								url: arr[i]
							});
						}
					}
				} else {
					//报错了
					_this.$u.toast(res.msg);
				}
			});
		}
	}
</script>

<style>
	page {
		background-color: #fff;
	}
</style>

<style lang="scss" scoped>
	.storeSetting {
		/deep/ .u-button {
			background-color: #D0241C;
			color: #fff;
			height: 70rpx;
			border-radius: 26rpx;
		}

		/deep/ .u-input {
			border: none !important;
		}

		/deep/ .u-input {
			input {
				text-align: right !important;
			}
		}

		/deep/ .u-textarea {
			border: none !important;
		}

		/deep/.u-form-item__body__left__content__label {
			font-size: 30rpx !important;
			width: 190rpx !important;
		}


		/deep/ .u-upload__wrap {
			justify-content: flex-end;
		}
	}
</style>